// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// l [author] rhyme_lph
// g [email]  rhymelph@gmail.com
// p [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/purchases_summary_entity.dart';
import 'package:finance_app/src/entities/transaction_entity.dart';
import 'package:finance_app/src/http_service/http_dashboard_service.dart';
import 'package:finance_app/src/mixin/refresh_mixin.dart';
import 'package:finance_app/src/mixin/time_sort_mixin.dart';
import 'package:finance_app/src/mixin/transaction_data_mixin.dart';
import 'package:finance_app/src/provider/dashboard/purchase/purchases_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:flutter/material.dart';

class PurchasesSummaryProvider extends BaseProvider<PurchasesSummaryEntity>
    with
        TimeSortMixin<PurchasesSummaryEntity>,
        TransactionDataMixin<PurchasesSummaryEntity>,
        RefreshMixin<PurchasesSummaryEntity, List<TransactionEntity>> {
  ScrollController controller = ScrollController();

  @override
  void initState() {
    super.initState();
    controller.addListener(() {
      getParentProvider<PurchasesProvider>().handleScrollUpdate(controller);
    });
  }

  @override
  List<String> get types => [
        if (Config.hasPermission(PermissionUtils.purchaseOrder))
          'purchase_order',
        if (Config.hasPermission(PermissionUtils.bill)) 'bill',
        if (Config.hasPermission(PermissionUtils.expense)) 'expense'
      ];

  @override
  Future get dataFuture => HttpDashboardService.dashboardPurchases();

  void onNavOpenPurchaseOrder() {
    Routes.navigateTo(RouterGenProviders.allTransactionsPage,
        params: {'type': 4, 'initFilter': 'Open PO'});
  }

  void onNavViewAll() {
    Routes.navigateTo(RouterGenProviders.allTransactionsPage, params: {
      'type': 3,
    });
  }

  @override
  void unFocus() {}

  @override
  List<TransactionEntity> get dataList => transactionList;

  void onNavUnpaidBill() {
    Routes.navigateTo(RouterGenProviders.allTransactionsPage,
        params: {'type': 8, 'initFilter': 'Unpaid Bill,Unpaid Expense'});
  }

  void onNavOverdueBill() {
    Routes.navigateTo(RouterGenProviders.allTransactionsPage,
        params: {'type': 8, 'initFilter': 'Overdue Bill,Overdue Expense'});
  }

  @override
  void onTransactionDeleted() {
    onRefresh();
  }

  @override
  Future<void> onRefresh() async {
    await post(dataFuture, onSuccess: (result) {
      data = getEntityFromResult<PurchasesSummaryEntity>(result);
      update();
    }, autoHandler: AutoHandler.Toast);
    return super.onRefresh();
  }
}
